package com.quanyan.user.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.quanyan.api.APIResponse;
import com.quanyan.user.mapper.TbUserFollowMapper;
import com.quanyan.user.model.db.TbUserFollow;
import com.quanyan.user.model.db.TbUserFollowExample;
import com.quanyan.user.model.db.TbUserFriend;
import com.quanyan.user.request.ReqUserFollow;
import com.quanyan.user.response.RespUserFollow;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.service.UserFollowService;
import com.quanyan.user.service.UserFriendService;
import com.quanyan.user.service.UserQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/16.
 */
@Service
public class UserFollowServiceImpl implements UserFollowService {
    private static final Logger logger = LoggerFactory.getLogger(UserFollowServiceImpl.class);


    @Autowired
    private TbUserFollowMapper tbUserFollowMapper;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private UserFriendService userFriendService;



    public List<TbUserFollow> batchUserFollow(Integer uid ,List<Integer> lstFollowId){
//        List<TbUserFollow> result = new ArrayList<>();
//        List<Integer> dbUid = new ArrayList<>();

//        for (Integer friendUid : lstFollowId ){ //查询缓存
//            String key = UserConstants.getFriendRemark(uid,friendUid);
//            TbUserFollow tbUserFollow = (TbUserFollow)myRedisTemplate.get(key);
//            if(tbUserFollow != null  && tbUserFollow.getState() == follow_state_true )//0 关注
//                result.add(tbUserFollow);
//            else if(tbUserFollow == null)
//                dbUid.add(friendUid);
//        }

        //if(dbUid.size() > 0 ){ //查询数据库
            TbUserFollowExample tbUserFollowExample = new TbUserFollowExample();
            TbUserFollowExample.Criteria criteria = tbUserFollowExample.createCriteria();
            criteria.andUidEqualTo(uid);
            criteria.andFollowIdIn(lstFollowId);
            criteria.andStateEqualTo(follow_state_true);
            List<TbUserFollow> lst = tbUserFollowMapper.selectByExample(tbUserFollowExample);
//            if(lst != null && lst.size() > 0){
//               for (TbUserFollow tbUserFollow : lst){ //添加到缓存
//                   result.add(tbUserFollow);
//                   String key = UserConstants.getFriendRemark(uid,tbUserFollow.getFollowId());
//                   myRedisTemplate.set(key,tbUserFollow , 7);
//               }
//            }
        //}
        return lst;
    }


    public TbUserFollow getTbUserFollow(Integer uid ,Integer followId) {
        TbUserFollowExample tbUserFollowExample = new TbUserFollowExample();
        TbUserFollowExample.Criteria criteria = tbUserFollowExample.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andFollowIdEqualTo(followId);
        criteria.andStateEqualTo(follow_state_true);
        List<TbUserFollow> lst = tbUserFollowMapper.selectByExample(tbUserFollowExample);
        if (lst != null && lst.size() > 0)
            return lst.get(0);
        return null;
    }



    public Map<Integer,TbUserFollow> batchUserFollowMap (Integer uid ,List<Integer> lstFollowId){
        List<TbUserFollow> lst = this.batchUserFollow(uid,lstFollowId);
        Map<Integer,TbUserFollow> map = new HashMap<>();
        if (lst!=null && lst.size() > 0)
            map = Maps.uniqueIndex(lst, this.indexOriginDtoByVendorItemId());
        return map;
    }


    public Function<TbUserFollow, Integer> indexOriginDtoByVendorItemId() {
        return new Function<TbUserFollow, Integer>() {
            @Override
            public Integer apply(TbUserFollow input) {
                return input.getFollowId();
            }
        };
    }

    /**
     * 关注指定用户
     *
     * @param uid
     * @param followUid
     * @return
     */
    @Override
    @Transactional
    public APIResponse followUser(Integer uid, Integer followUid) {
        try {
            List<TbUserFollow> userFollows = getFollowedUser(uid, followUid);
            if (userFollows != null && userFollows.size() > 0) {
                return APIResponse.returnFail("已经关注该用户了");
            }
            TbUserFollow tbUserFollow = new TbUserFollow();
            tbUserFollow.setUid(uid);
            tbUserFollow.setFollowId(followUid);
            tbUserFollow.setState(follow_state_true);
            tbUserFollow.setCreateTime((int)(System.currentTimeMillis()/1000));
            tbUserFollow.setUpdateTime((int)(System.currentTimeMillis()/1000));
            tbUserFollowMapper.insertSelective(tbUserFollow);
        } catch (Exception e) {
            logger.error("关注好友失败！：{}",e.getMessage());
            return APIResponse.returnFail("关注好友失败!");
        }

        return APIResponse.returnSuccess();
    }


    /**
     * 取消关注指定用户
     *
     * @param uid
     * @param followUid
     * @return
     */
    @Override
    @Transactional
    public APIResponse cancelFollowUser(Integer uid, Integer followUid) {
        try {
            List<TbUserFollow> userFollows = getFollowedUser(uid, followUid);

            if (userFollows != null && userFollows.size() > 0) {
                TbUserFollowExample userFollowExample = new TbUserFollowExample();
                TbUserFollowExample.Criteria criteria = userFollowExample.createCriteria();
                criteria.andUidEqualTo(uid);
                criteria.andFollowIdEqualTo(followUid);
                TbUserFollow userFollow = new TbUserFollow();
                userFollow.setState((byte)1);
                tbUserFollowMapper.updateByExampleSelective(userFollow,userFollowExample);
            }
        } catch (Exception e) {
            logger.error("取消好友关注失败！：{}", e.getMessage());
            return APIResponse.returnFail("取消关注好友失败!");
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 获取用户关注关系
     *
     * @param uid
     * @param followUid
     * @return
     */
    private List<TbUserFollow> getFollowedUser(Integer uid, Integer followUid) {
        TbUserFollowExample example = new TbUserFollowExample();
        TbUserFollowExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andFollowIdEqualTo(followUid);
        criteria.andStateEqualTo((byte)0);
        return tbUserFollowMapper.selectByExample(example);
    }

    public List<RespUserFollow> queryUserFriend(ReqUserFollow reqUserFollow){
        logger.info("查询好友列表{}",reqUserFollow.toString());
        Integer uid = reqUserFollow.getUid();
        List<Integer> lstFid = reqUserFollow.getLstFriendUid();
        Map<Integer,RespUserInfoBase> mapUserInfo = userQueryService.batchQueryUserInfoToMap(lstFid);
        Map<Integer,TbUserFollow> mapFollow = new HashMap<>();
        if (uid != null )
           mapFollow = this.batchUserFollowMap(uid, lstFid);
        Map<Integer,TbUserFriend> mapFriend =  userFriendService.batchUserFriendServiceToMap(uid,lstFid);
        List<RespUserFollow> result = null ;
        if (lstFid.size() > 0 ){
            result = new ArrayList<>();
            for ( Integer fid : lstFid ){
                RespUserFollow respUserFollow = new RespUserFollow();
                respUserFollow.setRespUserInfoBase(mapUserInfo.get(fid));
                if (mapFollow.containsKey(fid))
                    respUserFollow.setIsFollow((byte)1);
               if (mapFriend.containsKey(fid))
                    respUserFollow.setIsFriend((byte)1);
                result.add(respUserFollow);
            }
        }
        return result;
    }

    public APIResponse<List<RespUserFollow>> queryUserFriendService(ReqUserFollow reqUserFollow){
        try {
            if(reqUserFollow.getLstFriendUid() == null && reqUserFollow.getLstFriendUid().size()  < 1)
                return APIResponse.returnFail("缺少非必要参数！");
            return APIResponse.returnSuccess(this.queryUserFriend(reqUserFollow));
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }

    public APIResponse<List<Integer>> batchIsUserFollow (Integer uid ,List<Integer> lstFollowId){
        if( lstFollowId == null){
            return APIResponse.returnFail("lstFollowId 不能为空！");
        }
        List<Integer> followId = new ArrayList<>();
        if (uid != null){
            try {
                List<TbUserFollow> list = this.batchUserFollow(uid,lstFollowId);
                followId.addAll(this.testTransform(list));
            } catch (Exception e) {
                logger.error("{}",e);
                return APIResponse.returnFail("系统异常！");
            }
        }
        return APIResponse.returnSuccess(followId);
    }


    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> testTransform(List<TbUserFollow> list) {
        return ImmutableMultiset.copyOf(Lists.transform(list, new Function<TbUserFollow, Integer>() {
                    @Override
                    public Integer apply(TbUserFollow input) {
                        return input.getFollowId();
                    }
                }
        ));
    }
}
